#include "mystdio.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

//创建文件
MyFile* BuyFile(int fd, int flag)
{
    MyFile* f = (MyFile*)malloc(sizeof(MyFile));
    if(f == NULL)
    {
        return NULL;
    }

    f->fileno = fd;
    f->flag = flag;
    f->bufferlen = 0;
    f->flush_method = LINE_FLUSH;
    memset(f->outbuffer, 0, sizeof(f->outbuffer));

    return f;
}


//打开文件
MyFile* MyFopen(const char* path, const char* mode)
{
    int fd = -1;
    int flag = 0;
    if(strcmp(mode, "w"))//只写打开
    {
         flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode, "a"))//追加打开
    {
        flag = O_CREAT | O_WRONLY | O_APPEND; 
        fd = open(path,  flag, 0666);
    }
    else if(strcmp(mode, "r"))//只读打开
    {
        flag = O_RDWR;
        fd = open(path, flag);
    }

    if(fd < 0)
    {
        return NULL;
    }

    return BuyFile(fd, flag);
}

//关闭文件
void MyFclose(MyFile* f)
{
    if(f->fileno < 0)
    {
        return;
    }
    //刷新文件
    MyFFlush(f);

    close(f->fileno);

    //释放MyFile申请的空间
    free(f);
    f=NULL;
}

//写文件
int MyFwrite(MyFile* f, void* str, int len)
{
    //拷贝对应字符串
    memcpy(f->outbuffer + f->bufferlen, str, len);
    f->bufferlen += len;

    //刷新
    if(f->flush_method & LINE_FLUSH && f->outbuffer[f->bufferlen-1] == '\n')
    {
        MyFFlush(f);
    }

    return 0;
}


//刷新
void MyFFlush(MyFile* f)
{
    if(f->bufferlen < 0)
    {
        return;
    }

   int i = write(f->fileno, f->outbuffer, f->bufferlen);
    f->bufferlen = 0;
}


